import React, { useState, useEffect } from 'react';
import './banner.less';
import { host } from '../utils/utils';
import {
    Table,
    Space,
    Button,
    Modal,
    Form,
    Input,
    Radio,
    Popconfirm,
    Upload,
    message,
    Tag,
    Image,
} from 'antd';
import { request } from 'umi';
import { FormOutlined, UploadOutlined } from '@ant-design/icons';
const { TextArea } = Input;
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};
const Type = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [listData, setListData] = useState([]);
    const [loading, setloading] = useState(false);
    const [saveId, setSaveId] = useState(0);
    const [pageData, setPageData] = useState({
        pageSize: 10,
        current: 1,
        total: 0,
    });

    const [form] = Form.useForm();

    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            wdith: 80,
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            wdith: 300,
        },
        {
            title: '图片',
            key: 'picture',
            dataIndex: 'picture',
            width: 110,
            render: (text, record) => {
                return (
                    <Image.PreviewGroup>
                        <Image width={100} height={100} src={`${host}/storage/${text}`} />
                    </Image.PreviewGroup>
                );
            },
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <a
                        onClick={() => {
                            setSaveId(record.id);
                            setIsModalVisible(true);

                            let imgFileArr = [];
                            imgFileArr.push({
                                uid: record.picture,
                                name: record.picture,
                                status: 'done',
                                response: {
                                    data: record.picture,
                                },
                                url: `${host}/storage/${record.picture}`,
                            });

                            form.setFieldsValue({
                                name: record.name,
                                info_id: record.info_id,
                                picture: imgFileArr,
                            });
                        }}
                    >
                        修改
                    </a>
                    <Popconfirm
                        placement="bottomRight"
                        title={'确认删除？'}
                        onConfirm={() => {
                            setloading(true);
                            request(`${host}/v1.0/api/Type/delete`, {
                                method: 'post',
                                data: {
                                    id: record.id,
                                },
                            }).then((res) => {
                                if (res.code == 200) {
                                    getList(pageData.current);
                                }
                            });
                        }}
                        okText="Yes"
                        cancelText="No"
                    >
                        <a style={{ color: 'red' }}>删除</a>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    const getList = (page) => {
        request(`${host}/v1.0/api/Type/list`, {
            method: 'get',
            params: {
                page: page,
            },
        }).then((res) => {
            if (res.code == 200) {
                setListData(res.data.data);
                setPageData({
                    pageSize: 10,
                    current: res.data.current_page,
                    total: res.data.total,
                });
                setloading(false);
            }
        });
    };

    useEffect(() => {
        getList(1);
    }, []);

    const showModal = () => {
        setIsModalVisible(true);
        setSaveId(0);
        form.resetFields();
    };

    const handleOk = () => {
        setIsModalVisible(false);
        // 获取form的值
        console.log(form.getFieldsValue());
        let fromData = form.getFieldsValue();

        let data = {
            name: fromData.name,
            picture: fromData.picture[0].response.data,
            info_id: fromData.info_id,
        };

        if (saveId > 0) {
            data.id = saveId;
        }

        request(`${host}/v1.0/api/Type/save`, {
            method: 'post',
            data: data,
        }).then((res) => {
            if (res.code == 200) {
                getList(pageData.current);
                message.success('成功!');
            }
        });
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const props = {
        name: 'file',
        action: `${host}/v1.0/api/key/upload`,
        onChange(info) {
            // console.log(info);
            if (info.file.status !== 'uploading') {
                // console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                // message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        multiple: true,
    };

    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    return (
        <div className="Banner">
            <div className="btnGroup">
                <Button
                    type="primary"
                    onClick={showModal}
                    icon={<FormOutlined />}
                >
                    新建分类
                </Button>
            </div>
            <Table
                columns={columns}
                dataSource={listData}
                rowKey="id"
                loading={loading}
                pagination={{
                    pageSize: pageData.pageSize,
                    current: pageData.current,
                    total: pageData.total,
                    showSizeChanger: false,
                    onChange: (page) => {
                        setloading(true);
                        getList(page);
                    },
                }}
            />
            <Modal
                title="Type"
                visible={isModalVisible}
                onOk={handleOk}
                width={800}
                onCancel={handleCancel}
            >
                <Form {...layout} form={form}>
                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{ required: true }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="图片"
                        name="picture"
                        valuePropName="fileList"
                        rules={[{ required: true }]}
                        getValueFromEvent={normFile}
                    >
                        <Upload {...props} accept="image/*">
                            <Button icon={<UploadOutlined />}>点击上传</Button>
                        </Upload>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default Type;
